﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace TbDataSync
{
    public partial class Program
    {

        /// <summary>
        /// 获取设备Token
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static string GetToken(string deviceId, HttpClient httpClient)
        {
            var token_url = urls["get_token"].Replace("%deviceId%", deviceId);
            var tokenResult = httpClient.GetAsync(token_url).Result.Content.ReadAsStringAsync().Result;
            var token = JsonConvert.DeserializeObject<TokenResult>(tokenResult).credentialsId;
            return token;
        }

        /// <summary>
        /// 根据设备名搜索设备
        /// </summary>
        /// <param name="deviceName"></param>
        /// <param name="httpClient"></param>
        /// <returns></returns>
        public static SearchDeviceResult SearchDevice(string deviceName, HttpClient httpClient)
        {
            var searchUrl = urls["search_device"].Replace("%deviceName%", deviceName);
            var searchRes = httpClient.GetAsync(searchUrl).Result;
            if (searchRes.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var resp = searchRes.Content.ReadAsStringAsync().Result;
                var result = JsonConvert.DeserializeObject<SearchDeviceResult>(resp);
                return result;
            }

            return new SearchDeviceResult() { data = new List<AddDeviceResult>() };
        }


        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="deviceName">设备名</param>
        /// <param name="label">标签</param>
        /// <returns>设备ID</returns>
        public static string AddDevice(string deviceName, string label)
        {
            if (ramdomDeviceName)
            {
                deviceName = Guid.NewGuid().ToString();
            }

            var applyResp = new_client.GetAsync(urls["apply_device"]).Result;
            if (applyResp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var applyResult = applyResp.Content.ReadAsStringAsync().Result;
                var apply = JsonConvert.DeserializeObject<ApplyResult>(applyResult);
                var profileId = apply.id.id;

                var param = new AddDeviceParam()
                {
                    additionalInfo = new AdditionalInfo()
                    {
                        description = "",
                        gateway = false,
                        overwriteActivityTime = false
                    },
                    customerId = null,
                    deviceProfileId = new DeviceProfileId()
                    {
                        entityType = "DEVICE_PROFILE",
                        id = profileId
                    },
                    label = label,
                    name = deviceName
                };
                var content = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8, "application/json");
                var addDeviceResp = new_client.PostAsync(urls["add_device"], content).Result;

                if (addDeviceResp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var addDeviceResult = addDeviceResp.Content.ReadAsStringAsync().Result;
                    var addDevice = JsonConvert.DeserializeObject<AddDeviceResult>(addDeviceResult);

                    Log.Info($"新TB设备已添加 设备ID:{addDevice.id.id}");
                    return addDevice.id.id;
                }
                else
                {
                    var err = addDeviceResp.Content.ReadAsStringAsync().Result;
                    var err_decode = JsonConvert.DeserializeObject<ResponseResultErr>(err);
                    //记录失败的设备
                    LogFailedDevice(deviceName, err_decode);

                    if (err_decode.errorCode == 31)
                    {
                        //如果是设备重复，则获取同名设备，正常推数据
                        var result = SearchDevice(deviceName, new_client);
                        if (result.data.Count > 0)
                        {
                            Log.Info($"设备 {deviceName} 已存在，将只推送数据");
                            return result.data.FirstOrDefault().id.id;
                        }

                        Log.Info($"新TB设备添加失败,数据未推送 设备名称:{deviceName},错误信息:重复设备未取到");
                    }
                    else
                    {
                        Log.Info($"新TB设备添加失败 设备名称:{deviceName},错误信息:{err_decode.message}");
                    }
                }
                return string.Empty;
            }
            else
            {
                Login();
                return AddDevice(deviceName, label);
            }
        }

    }
}
